<template>
    <u-input class="box-input" ref="input" v-model="localValue" type="number" :placeholder="placeholder"
        :disabled="disabled" :readonly="readonly" :clearable="clearable" :maxlength="maxlength" @blur="blur"
        @input="input">
        <template slot="suffix">
            <slot name="suffix"></slot>
        </template>
    </u-input>
</template>

<script>
    export default {
        name: 'MyNumber',
        props: {
            value: {
                type: [String, Number],
                default: ''
            },
            placeholder: {
                type: String,
                default: '请输入'
            },
            disabled: {
                type: Boolean,
                default: false
            },
            readonly: {
                type: Boolean,
                default: false
            },
            clearable: {
                type: Boolean,
                default: false
            },
            maxlength: {
                type: Number,
                default: -1
            },
            min: {
                type: Number,
                default: -1
            },
            max: {
                type: Number,
                default: -1
            },
            decimal: {
                type: Number,
                default: 0
            },
            halfAdjust: {
                type: Boolean,
                default: true
            },
        },
        data() {
            return {
                localValue: this.value,
            }
        },
        watch: {
            value() {
                this.$set(this, 'localValue', this.value);
            },
        },
        methods: {
            input(value) {
                this.$emit('input', value);
            },
            blur() {
                let realValue = this.localValue
                if (realValue !== '') {
                    if (this.halfAdjust) {
                        realValue = parseFloat(parseFloat(realValue).toFixed(this.decimal));
                    } else {
                        const number = parseFloat(parseFloat(realValue))
                        const dem = Math.pow(10, this.decimal)
                        realValue = Math.floor(number * dem) / dem
                    }

                } else {
                    if (this.min !== -1) {
                        realValue = this.min;
                    }
                }
                if (this.min !== -1 && realValue < this.min) {
                    realValue = this.min;
                }
                if (this.max !== -1 && realValue > this.max) {
                    realValue = this.max;
                }
                this.$set(this, 'localValue', realValue)
                this.$emit('input', this.localValue);
                this.$emit('blur');
            },
        },
    };
</script>